package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.dto.PayOrderDTO;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName:PayController
 * Package:com.huiminpay.transaction.controller
 * Time: 2024/7/29
 */
@Controller
@Slf4j
@Api(tags = "支付")
public class PayController {
    @Resource
    TransactionService transactionService;

    @Reference
    AppService appService;

    @ApiOperation(value = "支付页面")
    @RequestMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) {
        try {
            if (request == null) {
                throw new IllegalArgumentException("HttpServletRequest cannot be null");
            }

            String ticketStr = EncryptUtil.decodeUTF8StringBase64(ticket);
            PayOrderDTO orderDTO = JSON.parseObject(ticketStr, PayOrderDTO.class);

            String userAgent = request.getHeader("user-agent");
            if (userAgent == null) {
                userAgent = ""; // 避免BrowserType.valueOfUserAgent因null值而抛出异常
            }
            BrowserType browserType = BrowserType.valueOfUserAgent(userAgent);

            switch (browserType) {
                case ALIPAY:
                    return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(orderDTO);
                case WECHAT:
                    // 假设已实现微信支付获取授权码的逻辑
                    return "forward:/wechat-pay-page?" + ParseURLPairUtil.parseURLPair(orderDTO);
                default:
                    return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(orderDTO);
            }
        } catch (Exception e) {
            log.error("支付页面跳转失败", e); // 使用日志框架记录异常信息和堆栈跟踪
            return "forward:/pay_error";
        }
    }

    @ApiOperation(value = "支付宝门店下单付款")
    @PostMapping(value = "/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO,
                                          HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {
        //支付宝的下单接口，前端订单确认界面，点击确认支付，跳转到支付宝支付页面
        //1. 获取订单信息
        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2dto(orderConfirmVO);
        //应用id
        String appId = payOrderDTO.getAppId();

        //获取下单的应用信息
        AppDTO appDTO = appService.queryAppById(appId);
        //获取商户信息
        payOrderDTO.setMerchantId(appDTO.getMerchantId());

        //将前端输入的 金额，转换成分
        payOrderDTO.setTotalAmount(Integer.parseInt(AmountUtil.changeY2F(orderConfirmVO.getTotalAmount())));
        //设置客户端ip
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        //保存订单，调用支付渠道代理服务的支付宝下单
        PaymentResponseDTO<String> paymentResponseDTO = transactionService.submitOrderByAli(payOrderDTO);
        //2. 支付宝接口响应
        String content = paymentResponseDTO.getContent();
        //3. 返回给前端
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(content); // 返回给支付宝的html页面
        response.getWriter().flush();
        response.getWriter().close();

    }


}
